<template>
  <div>
    <van-search
      v-model="value"
      shape="round"
      placeholder="请输入搜索关键词"
      @input="onInput"
    />
    <!--    热门搜索布局-->
    <div v-if='!list.length'>
      <div class="title">
        热门搜索
      </div>
      <!--      热门搜索标签-->
      <van-tag
        @click="onClickTags(item.first)"
        v-for="item in HotSearchList" :key="item.first"
        round
        plain
        color='#ccc'
        size="large"
        text-color="#333"
        type="primary">
        {{ item.first }}
      </van-tag>
    </div>

    <!--    搜索的列表-->
    <div v-else>
      <div class="title">
        最佳匹配
      </div>
      <!--      搜索结果-->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ceil v-for="item in list"
              :key="item.id"
              :authorName="item.ar[0].name"
              :id='item.id'
              :name="item.name"></ceil>
      </van-list>
    </div>

  </div>
</template>

<script>
import { getHotSerach, getSearchRes } from '@/api/search'
import ceil from '@/components/ceil'

export default {
  name: 'Search',
  data () {
    return {
      value: '',
      HotSearchList: [],
      list: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  components: {
    ceil
  },
  created () {
    this.getHotSongs()
  },
  methods: {
    async getHotSongs () {
      const res = await getHotSerach()
      this.HotSearchList = res.data.result.hots
    },
    // 搜索之后的触发的函数
    async onLoad () {
      this.page++
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10,
        offset: (this.page - 1) * 10
      })
      this.list.push(...res.data.result.songs)
      this.loading = false
      if (!res.data.result.songCount) {
        this.finished = true
      }
    },

    async onClickTags (songName) {
      this.value = songName
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10
      })
      this.list.push(...res.data.result.songs)
    },

    onInput () {
      if (!this.value) {
        this.list = []
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.value) return
        const res = await getSearchRes({
          keywords: this.value,
          limit: 10
        })
        this.list.push(...res.data.result.songs)
      }
      , 700)
    }
  }
}

</script>

<style scoped>
.van-tag {
  margin: 5px 10px;
}
</style>
